package com.luguangtao.controller;

import com.luguangtao.dao.UserJpaDao;
import com.luguangtao.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Optional;

/**
 * @类名: com.luguangtao.controller
 * @作者: lgt
 * @创建时间: 2019-12-18 09:03
 * @描述:
 **/
//控制层
@RestController
@CrossOrigin
public class UserController {
    //注入userjpa接口
    @Autowired
    UserJpaDao userJpaDao;
    //注入mongo
    @Autowired
    MongoTemplate mongoTemplate;

    //用户列表分页展示
    @RequestMapping("lists")
    public Page<User> lists(@RequestParam(defaultValue = "1")Integer pageNum,@RequestParam String name,@RequestParam String birth){
        if (name!=null && name!=""){
            Page<User> byNameLike = userJpaDao.findByNameLike(PageRequest.of(pageNum - 1, 3), "%" + name + "%");
            return byNameLike;
        }else if (birth!=null && birth!=""){
            Page<User> byBirth = userJpaDao.findByBirth(PageRequest.of(pageNum - 1, 3), birth);
            return byBirth;
        }else{
            Page<User> all = userJpaDao.findAll(PageRequest.of(pageNum - 1, 3));
            return all;
        }
    }

    //添加
    @RequestMapping("addUser")
    public int addUser(@RequestBody User user){
        User save = userJpaDao.save(user);

       // 10.	新增用户向mongodb中添加一条日志
        HashMap<Object, Object> map = new HashMap<>();
        map.put("type","添加操作");
        map.put("dates",new Date());
        mongoTemplate.save(map,"z_user");

        if (save!=null){
            return 1;
        }else{
            return 0;
        }
    }

    //回显
    @RequestMapping("getUser")
    public User getUser(Long id){
        Optional<User> byId = userJpaDao.findById(id);
        return byId.get();
    }

   // 修改用户（5分），
   @RequestMapping("updateUser")
   public int updateUser(@RequestBody User user){
       User user1 = userJpaDao.saveAndFlush(user);

      // 修改用户向mongodb中添加一条日志（5分）
       HashMap<Object, Object> map = new HashMap<>();
       map.put("type","修改操作");
       map.put("dates",new Date());
       mongoTemplate.save(map,"z_user");

       if(user1!=null){
           return 1;
       }else{
           return 0;
       }
   }

    // 逻辑删除用户（5分）
    @RequestMapping("del")
    public int del(Long id){
        Optional<User> byId = userJpaDao.findById(id);
        User user = byId.get();
        user.setDelstatus(0);
        User user1 = userJpaDao.saveAndFlush(user);

       // 删除用户向mongodb中添加一条日志（5分
        HashMap<Object, Object> map = new HashMap<>();
        map.put("type","删除操作");
        map.put("dates",new Date());
        mongoTemplate.save(map,"z_user");

        if(user1!=null){
            return 1;
        }else{
            return 0;
        }
    }
}
